
$(function(){
	var hrefobj=GetRequest();
	
	if(hrefobj.source){
		window.location.href="web.html?sku_code="+hrefobj.sku_code;		
	}else{
		//校验是否登陆
		checkoutlogin();
	}
	//添加作品
	$(document).on("click",".creatalbum",function(){
		$("#loadtoast").show();
		baseAjax('other/work/add_work','POST',{sku_code:sku_code,user_id:user_id},function(data){
			$(".upload_num").text(0);
			$("#uploaderFiles").empty();
			product_id=data.data.product_id;
			workid=data.data.id;			
			UtilProperty[workid]=new Object;
			UtilProperty[workid].workerInfo=data.data;
			UtilProperty[workid].imageObj=new Object;
			var image_num=data.data.image_num;
			//var image_num='21-22';
			$(".myphotoalbum").hide();
			$(".uploadcon").show();		
			var small_image_num,large_image_num;
			if(image_num.indexOf(">=")>=0){
				small_image_num=image_num.split('=')[1];
				document.title="至少上传"+small_image_num+"张照片";
			}else if(image_num.indexOf("<=")>=0){
				large_image_num=image_num.split('=')[1];
				document.title="最多上传"+large_image_num+"张照片"
			}else if(image_num.indexOf("-")>=0){
				small_image_num=image_num.split('-')[0];
				large_image_num=image_num.split('-')[1];
				document.title="上传"+image_num+"张照片"
			}else if(image_num.indexOf(",")>=0){
				small_image_num=image_num.split(',')[0];
				large_image_num=image_num.split(',')[1];
				document.title="上传"+small_image_num+"或"+large_image_num+"张照片";
			}
			$("#uploaderInput").attr({"small_image_num":small_image_num,"large_image_num":large_image_num,"image_num":large_image_num});
			
			$("#loadtoast").hide();
			
			//在作品中展示新增加的作品
			showtoworklist(data.data,small_image_num,large_image_num);
		})

					
		
	})
	//选择作品
	$(document).on("click",".albumitem",function(){
		$(".album .albumitem").removeClass("onfoucs");
		$(".album").find(".albuminfo").fadeOut();
		$(this).addClass("onfoucs").find(".albuminfo").fadeIn();
		$(".myphotoalbum a.open_up").addClass("focus");
	})
	
	
	//删除作品
	$(document).on("click",".albumitem .a_close",function(event){
		event.stopPropagation();
		var elem=$(this).closest(".albumlist");
		if(elem.attr("status")>=1){
			dialogshow("提示",'已提交作品不允许删除');	
		}else if(elem.attr("status")==0){
		$(".isyes").text("删除").attr({"oper":"deletework","work_id":$(this).closest(".albumitem").attr("work_id")}).removeClass("default").addClass("primary").show();
		 dialogshow("提示",'您确定删除作品吗？');		 
		 $(".iscancel").text("取消").removeClass("primary").addClass("default");
		}
	})
	
	
	
	
	//打开已经生成的作品
	$('.myphotoalbum').on("click","a.open_up",function(event){
		if($(".albumitem").hasClass("onfoucs")){
		workid=$(".onfoucs").attr("work_id");
		product_id=$(".onfoucs").attr("product_id");
		$("#loadtoast").show();	
		opentype=1;	
		var itemwork=UtilProperty[workid];		
			if(itemwork.lay_list){
				//遍历布局列表
				lay_list();
			}else{
				//获取布局列表		
				lay_listajax();
			}
			if(itemwork.worker){
				if(itemwork.base64image){
					$("#singerFiles").empty();
					for(var i=0;i<itemwork.image_list.length;i++){
						var item=itemwork.image_list[i];
						var li_detial='';
						if(item.quality!=0){//照片的一边小于900    照片像素过低可能导致，图片模糊   0=正常；1=比例不符合；2=像素不符合
							li_detial='<div class="upload_i_worn"><i class="weui-icon-warn"></i> </div>';
						}
						li_detial=li_detial+'<div class="delimportimg"><i class="fa fa-close fa-fw"></i></div>';					
						var li='<li class="weui-uploader__file" name="'+item.image_id+'" imgw="'+item.width+'" imgh="'+item.height+'" quality="'+item.quality+'"><div class="upload_img"></div>'+li_detial+'</li>';
						$("#singerFiles").append(li);
						
					}
	 				//打开编辑作品页面并且合成相应的页面
					startgetcanvas()
				}else{
					//获取作品图片列表
					image_listajax();
				}
			}else{
				//作品页面初始化接口 并且生成作品
				initializationwork();
			}
		}
	})
	
	
})



//我的作品
var idarr=new Array;//所有的作品id 和 产品id
function getwork_list(){	
	baseAjax('other/work/work_list','GET',{user_id:user_id,sku_code:sku_code},function(data){
		$(".album").empty();
		var arr=data.data.sort(sortNumber);
		//var arr=testArr.sort(sortNumber);
		var newhtml="";
		var oldhtml="";
		var timenew=new Array;
		var timeOld=new Object;
		var litObj=new Object;			
		var tipshtml='<div class="albumlist albumend"><div class="timefigure"><span class="figurecircle"></span></div><div class="timeline"><span></span></div><div class="albumtip">没有更多了</div></div>';									
		var day=formatDate('');	
		var creathtml='<div class="albumlist" status="0" time="'+day+'">'+
							'<div class="timefigure"><span class="figurenum">'+day+'</span></div>'+
							'<div class="timeline"><span></span></div>'+
							'<div class="albumcontain">'+
								'<div class="creatalbum" style="width:'+album_wid+'px; height:'+album_wid+'px;">'+
								'<div class="creatalbumbtn a_font">'+						
									'<span style="height:'+album_wid+'px; line-height:'+parseInt(album_wid+19)+'px;">新建作品</span>'+
								'</div>'+						
								'</div>'+
							'</div>'+					
						'</div>';
		if(arr.length>0){
		for(var i=0; i<arr.length;i++){			
			var item=arr[i];
			UtilProperty[item.id]=new Object;
			UtilProperty[item.id].workerInfo=item;	
			var time=formatDate(item.add_time).toString();	
			var image_num=item.image_num;
			var small_image_num,large_image_num;
			var scale=album_wid/item.width;
			if(image_num.indexOf(">=")>=0){
				small_image_num=image_num.split('=')[1];				
			}else if(image_num.indexOf("<=")>=0){
				large_image_num=image_num.split('=')[1];				
			}else if(image_num.indexOf("-")>=0){
				small_image_num=image_num.split('-')[0];
				large_image_num=image_num.split('-')[1];				
			}else if(image_num.indexOf(",")>=0){
				small_image_num=image_num.split(',')[0];
				large_image_num=image_num.split(',')[1];				
			}
			var image_numstr;
			if(small_image_num&&large_image_num){
				image_numstr=small_image_num+'-'+large_image_num;
			}else{
				if(small_image_num){
					image_numstr=small_image_num;
				}else{
					image_numstr=large_image_num;
				}
			}
			
			if(item.status==0){
				
				if(timenew.length==0){
				newhtml='<div class="albumlist" status="'+item.status+'" time="'+time+'">'+
							'<div class="timefigure"><span class="figurenum">'+time+'</span></div>'+
							'<div class="timeline"><span></span></div>'+
							'<div class="albumcontain boxflexThu">'+
								'<div class="creatalbum" style="width:'+parseInt(scale*item.width)+'px; height:'+parseInt(scale*item.height)+'px;">'+
								'<div class="creatalbumbtn a_font">'+						
									'<span style="height:'+parseInt(scale*item.height)+'px; line-height:'+parseInt(scale*item.height+19)+'px;">新建作品</span>'+
								'</div>'+						
								'</div>'+
							'</div>'+					
						'</div>';						
					litObj[item.status]=new Object;
					litObj[item.status][time]='';
				}else{
					if($.inArray(time,timenew)<0){
					newhtml=newhtml+'<div class="albumlist" status="'+item.status+'" time="'+time+'">'+
						'<div class="timefigure"><span class="figurenum">'+time+'</span></div>'+
						'<div class="timeline"><span></span></div>'+
						'<div class="albumcontain boxflexThu">'+	
						'</div>'+				
					'</div>';
					
					}
				}
				timenew.push(time);
				var li='<div class="albumitem itemflexthree" style="width:'+parseInt(scale*item.width)+'px; height:'+parseInt(scale*item.height)+'px;" product_id="'+item.product_id+'" work_id="'+item.id+'" show_type="'+item.show_type+'"  print_type="'+item.print_type+'">'+
												'<div class="albumimg">'+													
												'</div>'+
												'<div class="albuminfo">'+
													'<div class="a_close"><i class="fa fa-close fa-fw"></i></div>'+
													'<div class="a_txt">'+image_numstr+'图/'+item.pages+'页</div>'+
												'</div>'+
											'</div>';
				if(litObj[item.status][time]==undefined){
					litObj[item.status][time]=li;
				}else{
					litObj[item.status][time]=litObj[item.status][time]+li;
				}
				
			}else if(item.status>=1){
				 if(!litObj[item.status]){
				 	litObj[item.status]=new Object;		
				 }
				if(JSON.stringify(timeOld) == "{}"){
						oldhtml='<div class="albumlist submitedalbum">'+
							'<div class="timefigure"><span class="figurecircle"></span></div>'+
							'<div class="timeline"><span></span></div>'+
							'<div class="albumtip">	已提交作品</div>'+											
						'</div>'+
						'<div class="albumlist" status="'+item.status+'" time="'+time+'">'+
							'<div class="timefigure"><span class="figurenum">'+time+'</span></div>'+
							'<div class="timeline"><span></span></div>'+							
							'<div class="albumcontain boxflexThu">'+								
							'</div>'+					
						'</div>';				
					//litObj[item.status]=new Object;					
				}else{
					//if($.inArray(time,timeOld)<0){
					if(!timeOld[item.status]){
					oldhtml=oldhtml+'<div class="albumlist" status="'+item.status+'" time="'+time+'">'+
						'<div class="timefigure"><span class="figurenum">'+time+'</span></div>'+
						'<div class="timeline"><span></span></div>'+
						'<div class="albumcontain boxflexThu">'+	
						'</div>'+				
					'</div>';
					}
				}				
				//timeOld.push(time);
				timeOld[item.status]=time;
				var li='<div class="albumitem itemflexthree" style="width:'+parseInt(scale*item.width)+'px; height:'+parseInt(scale*item.height)+'px;" product_id="'+item.product_id+'" work_id="'+item.id+'" show_type="'+item.show_type+'"  print_type="'+item.print_type+'">'+
												'<div class="albumimg">'+												
												'</div>'+
												'<div class="albuminfo">'+
													'<div class="a_close"><i class="fa fa-close fa-fw"></i></div>'+
													'<div class="a_txt">'+image_numstr+'图/'+item.pages+'页</div>'+
												'</div>'+
											'</div>';
				if(litObj[item.status][time]==undefined){
					litObj[item.status][time]=li;
				}else{
					litObj[item.status][time]=litObj[item.status][time]+li;
				}
			}
			var ido={product_id:item.product_id,work_id:item.id}
			idarr.push(ido);
		}
		//得到封面图
		getreadyworker();
		
		if(data.data.length==0){			
			$(".album").append(creathtml+tipshtml);			
		}else{
			newhtml=newhtml==''?creathtml:newhtml;
			$(".album").append(newhtml+oldhtml+tipshtml);
			for(var k in litObj){
				for(var i in litObj[k]){
					var list=litObj[k][i];				
					$('.albumlist[status="'+k+'"][time="'+i+'"] .albumcontain').append(list);
				}
			}
		}
		
		}else{
			$(".album").append(creathtml+tipshtml);	
			$("#loadtoast").hide();
			$(".myphotoalbum").show();
		}
	
	})
	
}


//获取布局列表
function lay_listajax(){
	baseAjax('other/work/lay_list','GET',{product_id:product_id},function(data){	
		if(UtilProperty[workid]==null){
			UtilProperty[workid]=new Object;
		}
		UtilProperty[workid].lay_list=data.data;
		//遍历布局列表
		lay_list();
	})
	
	
	
}
//遍历布局列表
function lay_list(){
	$(".layoutlist").empty();
	var laylist=UtilProperty[workid].lay_list;
	for(var i=0; i<laylist.length;i++){
		var item=laylist[i];
		var scale=$(".layoutlist").height()/item.height;
		var layout_width=item.width*scale;
		var layout_height=$(".layoutlist").height();
		var conthtm='';
		for( var k=0; k<item.control_list.length; k++){
			var list=item.control_list[k];
			var styletxt='position: absolute; top:'+list.coordinate_y*scale+'px; left: '+list.coordinate_x*scale+'px; width: '+list.width*scale+'px; height: '+list.height*scale+'px;'
			conthtm=conthtm+'<div class="layout_inner" style="'+styletxt+'"></div>';
		}
		
		var layhtml='<div class="layout_box"><div class="layout_list" style="width:'+layout_width+'px;height:'+layout_height+'px">'+conthtm+'</div></div>';
		$(".layoutlist").append(layhtml);
		
		
	}
	
	
}

//获取作品图片列表
function image_listajax(){	
	baseAjax('other/work/work_image_list','GET',{work_id:workid},function(data){
		if(UtilProperty[workid]==null){
			UtilProperty[workid]=new Object;
		}
		UtilProperty[workid].image_list=data.data;
		//遍历图片
		//image_list();
		placeImageObj();
	})
	
	
	
}




//校验是否登陆
function checkoutlogin(){
	var strcookie = document.cookie;//获取cookie字符串
	//var strcookie="user_id=1; token=HsXHnzdM2YxgruH4Jqqzds%252BDJmzzbVHV7BsTN9ALOdswPEtEZnScILqHfaOObK1xz48k2olAJt7QwN05ei%252Fliw%253D%253D";
	var arrcookie = strcookie.split("; ");//分割
	//遍历匹配
	for ( var i = 0; i < arrcookie.length; i++) {
		var arr = arrcookie[i].split("=");
		if (arr[0] == 'user_id'){
			user_id=arr[1];
		}
		if (arr[0] == 'token'){
			token=arr[1];
		}
	}
	sku_code=GetRequest().sku_code;
	$.cookie('sku_code', sku_code, {path: '/' }); 
	if(user_id&&token){		
		$.ajax({ 				  		
			url:baseUrl+'wechat/login/verifytoken',	
			type:'GET',	
			dataType:"json",		
			data:{},	
	        success:function(data){
	        	if(data.code!=200){
	        		if(data.code!=404){
	        			$.cookie('token', null); 
	        			$.cookie('user_id', null);
	        			/* clearCookie('token', '.29858960.qcloud.la');
    					 clearCookie('user_id', '.29858960.qcloud.la');*/
    					 $("#loadtoast .weui-mask_transparent").hide();
	        			$("#diatips").attr("checklogin","1");
				 		dialogshow("错误",data.description);	
	        		}	        		
				 	
				}else{
				sku_code=$.cookie('sku_code'); // 若cookie存在则返回'cookieValue'；若cookie不存在则返回null   
          		//出现现在去购买的按钮
          		if(skucodebuy[sku_code]!=undefined){
          			$("._submitbuy a").attr("href",skucodebuy[sku_code]);
          			$("._submitbuy").show();
          		}
					//我的作品
					//user_id=358;
					getwork_list();
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){	
					
						if(XMLHttpRequest.status==0){
							dialogshow("提示",'加载失败，请重新加载！');
							 if(!$("#loadtoast").is(":hidden")){
						 	$("#loadtoast").hide();
							 }
						}else{
							dialogshow("提示",XMLHttpRequest.status);	
						}
					
					
			}
    	});
	}else{
		window.location.href=baseUrl+'wechat/login';			
	}
	
}

//时间戳怎么转成日期格式
/* function getLocalTime(nS) {     
       return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, ".").replace(/日/g, " ");      
    } */
   
function formatDate(now) { 
	if(now!=""){
		var time=new Date(now*1000);
	}else{
		var time=new Date();
	}	 
	 var year = time.getFullYear();
	 var month = time.getMonth() + 1;
	/* var date = time.getDate();
	 var hour = time.getHours();
	 var minute = time.getMinutes();
	 var second = time.getSeconds();*/
	 return year + "." + (month<10?'0'+month:month);
 }
            

//把套餐配送的食品的FdNo排序
function sortNumber(a,b)
	{
	return a.add_time > b.add_time ? -1 : 1; // 这里改为大于号  
	//return a.add_time - b.add_time;
	}
	
	
//删除作品
function closedia(a){
	if($(a).attr("oper")=="deletework"){
		workid = $(a).attr("work_id")
		baseAjax('other/work/update_work', 'POST', {work_id: workid,is_delete: 1}, function(data) {
			$('.albumitem[work_id="'+workid+'"]').remove();
			var isshow = false;
			$(".album").find(".albuminfo").each(function(index, element) {
				if(!$(element).is(":hidden")) {
					isshow = true;
				}
			})
			$(a).removeClass("primary").addClass("default").removeAttr().hide();
			$(".myphotoalbum a.open_up").attr("class", isshow == true ? "open_up open_up_album focus" : "open_up open_up_album");
			diatipshide();
			 $(".iscancel").text("确定").removeClass("default").addClass("primary");
			 $(a).removeAttr("oper").removeAttr("work_id");
		})
	}else if($(a).attr("oper")=="changelayout"){
		
		var pageno=$(a).attr("pageno");
		var index=$(a).attr("index");
		//确定更改布局
		comfirmchangelayout(pageno,index);
		diatipshide();
		
	}
}


function getreadyworker(){	
	for(var i=0;i< idarr.length; i++){
		 workid=idarr[i].work_id;
		 product_id=idarr[i].product_id;
		//获取已经存在的作品的作品页面信息
		baseAjax('other/work/work_page_list','GET',{work_id:workid},function(data){
			
				if(UtilProperty[workid]==null){
					UtilProperty[workid]=new Object;
				}
				UtilProperty[workid].worker=data.data;			
				UtilProperty[workid].imageObj=new Object;
				if(UtilProperty[workid].worker.length>0){
					var item=UtilProperty[workid].worker[0];
					var mulitImg=[];									
					var isfla=false;
					var bgurl=item.background.image_url+bgsize_str;
					UtilProperty[workid].worker[0].background.ischange=false;											
					if(item.background_id!=0){// lym 2018.01.02 修改 图片加载 原先的的id标志转为url标志	
						UtilProperty[workid].worker[0].background.image_url=bgurl;	
						if(UtilProperty.background.backgroundimage[bgurl]==undefined){
							mulitImg.push(bgurl);
							UtilProperty.background.backgroundimage[bgurl]=null;
							isfla=true;
						}
					}
					for(k=0; k<item.control_list.length;k++){
						var element=item.control_list[k];			
						if(element.control_id==1){	
							if(element.element_list instanceof Array&&element.element_list.length>0){
							var list=element.element_list[0];							
							if(list.image_url!=""){//lym 2018 01.03  分享修改
								var img_url=list.image_url+imgsize_str;
								UtilProperty[workid].worker[0].control_list[k].element_list[0].image_url=img_url; // lym 2018.01.02 修改 图片加载 原先的的id标志转为url标志
								if($.inArray(img_url, mulitImg)==-1){
									mulitImg.push(img_url);										
									isfla=true;
								}
							}
							
							
							
							}

						
						}
					}
					if(isfla){						
						//判断图片是否完全加载完毕
						imagelistToObject(mulitImg,workid,function(){
							//判断是否所有作品的封面的图片都加载完毕
							startcover()							
						})
					}else{
						startcover();
					}
					
				}else{					
					baseAjax('other/work/init_work','GET',{work_id:workid,is_return:1},function(data){		
						UtilProperty[workid].worker=data.data;						
						var item=UtilProperty[workid].worker[0];
						var mulitImg=[];										
						var isfla=false;
						var bgurl=item.background.image_url+bgsize_str;
						UtilProperty[workid].worker[0].background.ischange=false;											
						if(item.background_id!=0){// lym 2018.01.02 修改 图片加载 原先的的id标志转为url标志	
							UtilProperty[workid].worker[0].background.image_url=bgurl;	
							if(UtilProperty.background.backgroundimage[bgurl]==undefined){
								mulitImg.push(bgurl);
								UtilProperty.background.backgroundimage[bgurl]=null;
								isfla=true;
							}
						}
						
						
					for(k=0; k<item.control_list.length;k++){
						var element=item.control_list[k];			
						if(element.control_id==1){	
							if(element.element_list instanceof Array&&element.element_list.length>0){
								var list=element.element_list[0];
								if(list.image_url!=""){//lym 2018 01.03  分享修改
									var img_url=list.image_url+imgsize_str;
									UtilProperty[workid].worker[0].control_list[k].element_list[0].image_url=img_url; // lym 2018.01.02 修改 图片加载 原先的的id标志转为url标志
									if($.inArray(img_url, mulitImg)==-1){
										mulitImg.push(img_url);										
										isfla=true;
									}
								}
							}

						
						}
					}
					if(isfla){						
						//判断图片是否完全加载完毕
						imagelistToObject(mulitImg,workid,function(){
							//判断是否所有作品的封面的图片都加载完毕
							startcover()							
						})
					}else{
						startcover();
					}
										
					})
					
				}	
				
				
			})	
		break;	
	}
	
	
}
//得到照片书封面
function workfristimg(i,workid,product_id){
		var item=UtilProperty[workid].worker[i];
		if(item.title=="封面"){
		var canvas=document.createElement("canvas");						
		var context=canvas.getContext("2d");
		var w=boxwindthheight.width;
		var h=boxwindthheight.height;
		var scale;		
		if(item.width / item.height > w / h) {
			scale=w/item.width;
		} else {
			scale=h/item.height;
		}
		canvas.height=item.height*scale;
		canvas.width=item.width*scale;		
		drawToCanvas(canvas,item,context,scale,false);		
		$('.albumitem[product_id="'+product_id+'"][work_id="'+workid+'"] .albumimg').html('<img src="'+canvas.toDataURL()+'"/>');
		}
	
	
}

//在作品中展示新增加的作品
function showtoworklist(item,small_image_num,large_image_num){
	var time=formatDate(item.add_time).toString();	
	var creathtm=$(".creatalbum").prop("outerHTML");
	var image_numstr;
		if(small_image_num && large_image_num) {
			image_numstr = small_image_num + '-' + large_image_num;
		} else {
			if(small_image_num) {
				image_numstr = small_image_num;
			} else {
				image_numstr = large_image_num;
			}
		}
	var scale=album_wid/item.width;
	var albumhtm='<div class="albumitem itemflexthree" style="width:'+parseInt(scale*item.width)+'px; height:'+parseInt(scale*item.height)+'px;" product_id="'+item.product_id+'" work_id="'+item.id+'" show_type="'+item.show_type+'"  print_type="'+item.print_type+'">'+
										'<div class="albumimg">'+													
										'</div>'+
										'<div class="albuminfo">'+
											'<div class="a_close"><i class="fa fa-close fa-fw"></i></div>'+
											'<div class="a_txt">'+image_numstr+'图/'+item.pages+'页</div>'+
										'</div>'+
								'</div>'
							'</div>';
		
	if($('.albumlist[status="0"][time="'+time+'"]').length==0){
		newhtml='<div class="albumlist" status="'+item.status+'" time="'+time+'">'+
							'<div class="timefigure"><span class="figurenum">'+time+'</span></div>'+
							'<div class="timeline"><span></span></div>'+
							'<div class="albumcontain boxflexThu">'+
								'<div class="creatalbum" style="width:'+parseInt(scale*item.width)+'px; height:'+parseInt(scale*item.height)+'px;">'+
								'<div class="creatalbumbtn a_font">'+						
									'<span style="height:'+parseInt(scale*item.height)+'px; line-height:'+parseInt(scale*item.height+19)+'px;">新建作品</span>'+
								'</div>'+						
								'</div>'+
								albumhtm+					
						'</div>';	
		$(".creatalbum").remove();
		$(".album").prepend(newhtml);
	}else{
		$(".creatalbum").after(albumhtm);
	}

}